<template>
  <el-tabs v-model="activeName" type="card">
    <el-tab-pane label="公海设置" name="setting">
      <el-form class="ml-7">
        <el-form-item>
          <span class="mr-3">启用自动放入公海</span>
          <el-switch v-model="settingData.customerPoolEnable" />
        </el-form-item>
        <el-form-item>
          <span class="mr-3">每天放入时间</span>
          <el-time-picker v-model="settingData.customerPoolDropTime" value-format="HH:mm:ss" />
        </el-form-item>
        <el-form-item>
          <span class="mr-3">在放入前</span>
          <InputNumber v-model="settingData.customerPoolTipDay" class="mr-3" />
          <span class="mr-3">天的</span>
          <el-time-picker
            v-model="settingData.customerPoolTipTime"
            value-format="HH:mm:ss"
            class="mr-3"
          />
          <span>提醒业务员及时跟进</span>
        </el-form-item>
        <el-form-item style="margin-bottom: 0px">
          <span>自动执行掉入时跳过节假日</span>
        </el-form-item>
        <el-form-item style="margin-bottom: 0px">
          <el-checkbox v-model="settingData.customerPoolSkipHoliday" />
          <span>跳过中国法定节假日（元旦、春节、清明、劳动节、端午、中秋、国庆）</span>
        </el-form-item>
        <el-form-item style="margin-bottom: 0px">
          <el-checkbox v-model="settingData.customerPoolSkipSaturday" />
          <span>跳过周六</span>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="settingData.customerPoolSkipSunday" />
          <span>跳过周日</span>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="submitSettingForm"
            style="display: flex; justify-content: center"
          >
            保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <el-tab-pane label="公海规则" name="rule">
      <el-button type="primary" plain @click="handleCreateRule" class="mb-2 ml-1">
        <Icon icon="ep:plus" /> 添加规则
      </el-button>
      <Table :columns="ruleColumns" :data="ruleData" @row-dblclick="handleRuleDblclick">
        <template #menu="{ row }">
          <context-menu-item label="修改" @click="handleMenuRuleUpdate(row)" />

          <context-menu-item label="删除" @click="handleMenuRuleDeleted(row)" />
        </template>
        <template #isEnable="{ row }">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="row.isEnable ? 0 : 1" />
        </template>
      </Table>
    </el-tab-pane>
    <el-tab-pane label="最大客户限制" name="max_limit"
      ><el-button type="primary" plain @click="handleCreateMaxLimit" class="mb-2 ml-1">
        <Icon icon="ep:plus" /> 添加规则
      </el-button>
      <Table :columns="maxLimitColumns" :data="maxLimitData" @row-dblclick="handleMaxLimitDblclick">
        <template #menu="{ row }">
          <context-menu-item label="修改" @click="handleMenuMaxLimitUpdate(row)" />

          <context-menu-item label="删除" @click="handleMenuMaxLimitDeleted(row)" />
        </template>
        <template #isEnable="{ row }">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="row.isEnable ? 0 : 1" />
        </template> </Table
    ></el-tab-pane>
  </el-tabs>
  <PoolRuleEdit ref="poolRuleEditRef" @success="queryRule()" />
  <PoolMaxLimitEdit ref="poolMaxLimitEditRef" @success="queryMaxLimit()" />
</template>
<script setup name="PoolSetting" lang="ts">
import * as settingGlobalApi from '@/api/setting/globalSetting'
import * as poolSettingApi from '@/api/setting/poolSetting'

import PoolRuleEdit from './PoolRuleEdit.vue'
import PoolMaxLimitEdit from './PoolMaxLimitEdit.vue'
import { DICT_TYPE } from '@/utils/dict'
import * as PostApi from '@/api/system/post/post'
import * as DeptApi from '@/api/system/dept/dept'
const deptList = ref<any[]>([]) // 树形结构
const postList = ref() // 岗位列表
const poolRuleEditRef = ref()
const poolMaxLimitEditRef = ref()
const message = useMessage() // 消息弹窗
const activeName = ref('setting')
const settingData = ref({
  customerPoolEnable: false,
  customerPoolDropTime: '23:00:00',
  customerPoolTipDay: 3,
  customerPoolTipTime: '10:00:00',
  customerPoolSkipHoliday: false,
  customerPoolSkipSaturday: false,
  customerPoolSkipSunday: false
})

const ruleColumns = ref([
  { label: '规则名称', prop: 'name' },
  {
    label: '部门',
    prop: 'ruleDepts',
    formatter: ({ ruleDepts }) =>
      ruleDepts
        .map((ruleDept) => {
          return ruleDept.dept.name
        })
        .toString()
  },
  {
    label: '岗位',
    prop: 'postIds',
    formatter: ({ rulePosts }) =>
      rulePosts
        .map((rulePost) => {
          return rulePost.post.name
        })
        .toString()
  },
  { label: '上次跟进时间超过天数', prop: 'lastFollowDay' },
  { label: '上次发邮件时间超过天数', prop: 'lastSendMailDay' },
  { label: '是否启用', prop: 'isEnable', slot: 'isEnable' }
])

const ruleData = ref()

const maxLimitColumns = ref([
  {
    label: '岗位',
    prop: 'postIds',
    formatter: ({ limitPosts }) =>
      limitPosts
        .map((limitPost) => {
          return limitPost.post.name
        })
        .toString()
  },
  {
    label: '客户状态',
    prop: 'isOnlyNoDeal',
    formatter: ({ isOnlyNoDeal }) => (isOnlyNoDeal ? '仅未成交客户' : '全部')
  },
  { label: '客户总数限制', prop: 'customerCountLimit' },
  { label: '是否启用', prop: 'isEnable', slot: 'isEnable' }
])

const maxLimitData = ref()

/** 初始化 */
onMounted(async () => {
  // 加载部门树
  deptList.value = await DeptApi.listAllSimple()

  // 加载岗位列表
  postList.value = await PostApi.listAllSimple()

  const customerPoolSetting = await settingGlobalApi.queryByClass('customerPool')
  customerPoolSettingConvertObject(customerPoolSetting)
  await queryRule()
  await queryMaxLimit()
})

const customerPoolSettingConvertObject = (customerPoolSetting) => {
  customerPoolSetting.forEach((setting) => {
    if (settingData.value[setting.settingKey] != undefined) {
      settingData.value[setting.settingKey] = setting.settingValue
    }
  })
}

const customerPoolSettingConvertArray = () => {
  let customerPoolSettingArr = [] as any[]
  Object.entries(settingData.value).forEach(([key, value]) => {
    if (value != undefined && value != '')
      customerPoolSettingArr.push({ settingKey: key, settingValue: value })
  })
  return customerPoolSettingArr
}

const submitSettingForm = async () => {
  await settingGlobalApi.update(customerPoolSettingConvertArray())
  message.success('修改成功')
}

const handleCreateRule = () => {
  poolRuleEditRef.value.open('create', 0)
}

const queryRule = async () => {
  ruleData.value = await poolSettingApi.queryRule()
}

const handleRuleDblclick = (row) => {
  poolRuleEditRef.value.open('update', row.id)
}

const handleMenuRuleUpdate = (row) => {
  poolRuleEditRef.value.open('update', row.id)
}

const handleMenuRuleDeleted = async (row) => {
  await poolSettingApi.deleteRule(row.id)
  message.success('删除成功')
  queryRule()
}

const handleCreateMaxLimit = () => {
  poolMaxLimitEditRef.value.open('create', 0)
}

const queryMaxLimit = async () => {
  maxLimitData.value = await poolSettingApi.queryMaxLimit()
}

const handleMaxLimitDblclick = (row) => {
  poolMaxLimitEditRef.value.open('update', row.id)
}

const handleMenuMaxLimitUpdate = (row) => {
  poolMaxLimitEditRef.value.open('update', row.id)
}

const handleMenuMaxLimitDeleted = async (row) => {
  await poolSettingApi.deleteMaxLimit(row.id)
  message.success('删除成功')
  queryMaxLimit()
}
</script>
<style scoped>
:deep(.el-tabs__nav-scroll) {
  display: flex;
  justify-content: center;
}
</style>
